import { createStore } from 'vuex'
import Cookie from 'js-cookie'

export default createStore({
    state: {
        isCollapse: true,
        currentMenu: null,
        tagsList: [
            {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 'home',
            }
        ],
        menu: {},
        token: '',
    },
    mutations: {
        updateCollapse(state, val) {
            state.isCollapse = !state.isCollapse
        },
        selectMenu(state, val) {
            //val.name == home ? (state.currentMenu = null) : (state.currentMenu = val)
            if (val.name == 'home') {
                state.currentMenu = null
            } else {
                state.currentMenu = val
                //console.log(state.currentMenu);
                let result = state.tagsList.findIndex((item) => item.name === val.name);
                result == -1 ? state.tagsList.push(val) : "";
            }

        },
        closeTag(state, val) {
            let result = state.tagsList.findIndex((item) => item.name === val.name)
            state.tagsList.splice(result, 1)

        },
        setMenu(state, val) {
            state.menu = val
            localStorage.setItem('menu', JSON.stringify(val))
        },
        addMenu(state, router) {
            if (!localStorage.getItem('menu')) {
                return
            }
            const menu = JSON.parse(localStorage.getItem('menu'))
            state.menu = menu
            //动态路由功能
            const menuArray = []
            menu.items.forEach(item => {
                if (item.children) {
                    item.children = item.children.map(item => {
                        let url = `../views/${item.url}.vue`
                        item.component = () => import(/* @vite-ignore */ url)
                        return item
                    })
                    menuArray.push(...item.children)
                } else {
                    let url = `../views/${item.url}.vue`
                    item.component = () => import(/* @vite-ignore */ url)
                    menuArray.push(item)
                }
            })
            menuArray.forEach(item => {
                router.addRoute('home1', item)
            })
            //console.log(router);
        },
        clearMenu(state) {
            state.menu = {}
            localStorage.removeItem('menu')
        },
        setToken(state, val) {
            state.token = val
            Cookie.set('token', val)
        },
        clearToken(state) {
            state.token = ''
            Cookie.remove('token')
        },
        getToken(state) {
            state.token = state.token || Cookie.get('token')
        }
    }
})